<template>
    <div class="role_page app-container">
        <div>
            <el-input v-model="searchKeyword" style="width: 30%; margin-right: 10px" placeholder="请输入角色名" @keyup.enter.native="handleSearch"></el-input>
            <el-button type="primary" @click="handleSearch"> 搜索 </el-button>
            <el-button type="primary" @click="handleAddRole"> 新增角色 </el-button>
        </div>
        <el-table :data="rolesList" style="width: 100%; margin-top: 30px" border>
            <el-table-column align="center" label="角色名" width="220">
                <template slot-scope="scope">
                    {{ scope.row.name }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间">
                <template slot-scope="scope">
                    {{ scope.row.time }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="handleEdit(scope)">
                        修改
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '修改' : '新增'" :close-on-click-modal="false" @closed="dialogCloseCallBack" width="40%">
            <div v-loading="loading">
                <el-form ref="roleForm" :model="role" :rules="rules" label-width="100px">
                    <el-form-item label="角色名" prop="name">
                        <el-input v-model="role.name" placeholder="请输入角色名" />
                    </el-form-item>
                    <el-form-item label="平台权限" prop="platformAuth">
                        <el-select v-model="role.platformAuth" placeholder="请选择平台权限" style="width: 100%" multiple collapse-tags filterable :reserve-keyword="true">
                            <el-option label="安卓" value="0"> </el-option>
                            <el-option label="ios" value="1"> </el-option>
                            <el-option label="小游戏" value="2"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="游戏权限" prop="gameAuth">
                        <el-select v-model="role.gameAuth" placeholder="请选择游戏权限" style="width: 100%" multiple collapse-tags filterable :reserve-keyword="true">
                            <el-option label="全部" value="all"> </el-option>
                            <el-option v-for="item in gameList" :key="item.gameId" :label="item.gameName" :value="item.gameId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="菜单权限">
                        <el-tree ref="tree" :data="routes" :props="defaultProps" :default-expand-all="true" :default-checked-keys="routesOpen" show-checkbox node-key="id" class="permission-tree" />
                    </el-form-item>
                </el-form>
                <div style="text-align: right">
                    <el-button type="danger" @click="dialogVisible = false"> 取消 </el-button>
                    <el-button type="primary" @click="confirmRole" :loading="submitLoading">
                        确认
                    </el-button>
                </div>
            </div>
        </el-dialog>
        <back-to-top />
    </div>
</template>

<script>
import { deepClone } from "@/utils";
import { getRoutes, getRoles, addRole, updateRole, getGameList } from "@/api/role";
import BackToTop from "@/components/BackToTop";
export default {
    name: "SystemRole",
    components: {
        BackToTop,
    },
    data () {
        return {
            role: {},
            routes: [],
            routesOpen: [],
            rolesList: [],
            rolesListCopy: [],
            dialogVisible: false,
            dialogType: "new",
            defaultProps: {
                children: "children",
                label: "name",
            },
            rules: {
                name: [{ required: true, message: "请输入角色名", trigger: "blur" }],
                gameAuth: [{ required: true, message: "请选择游戏权限", trigger: "change" }],
                platformAuth: [{ required: true, message: "请选择平台权限", trigger: "change" }],
            },
            loading: false,
            searchKeyword: "",
            submitLoading: false,
            gameList: [],
        };
    },
    computed: {},
    created () {
        this.getRoles();
    },
    watch: {
        "role.gameAuth": function (val, oldval) {
            if (val && oldval) {
                let newindex = val.indexOf("all"),
                    oldindex = oldval.indexOf("all"); //获取val和oldval里all的索引,如果没有则返回-1
                if (newindex != -1 && oldindex == -1 && val.length > 1)
                    //如果新的选择里有勾选了选择所有选择所有 则 只直线勾选所有整个选项
                    this.role.gameAuth = ["all"];
                else if (newindex != -1 && oldindex != -1 && val.length > 1)
                    //如果操作前有勾选了选择所有且当前也选中了勾选所有且勾选数量大于1  则移除掉勾选所有
                    this.role.gameAuth.splice(val.indexOf("all"), 1);
            }
        },
    },
    methods: {
        //获取权限列表
        async getRoles () {
            const res = await getRoles();
            res.data = res.data || [];
            this.rolesList = res.data.map((item) => {
                item.platformAuth
                    ? (item.platformAuth = item.platformAuth.split(","))
                    : (item.platformAuth = []);
                item.gameAuth
                    ? (item.gameAuth = item.gameAuth
                        .split(",")
                        .map((str) => (isNaN(Number(str)) ? "all" : Number(str))))
                    : (item.gameAuth = ["all"]);
                return item;
            });
            this.rolesListCopy = deepClone(this.rolesList);
        },
        handleSearch () {
            let keyWord = this.searchKeyword;
            this.rolesList = this.rolesListCopy.filter(
                (route) => route.name.indexOf(keyWord) != -1
            );
        },
        //新增角色
        handleAddRole () {
            this.role = {};
            this.$prompt("请输入角色名", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            })
                .then(async ({ value }) => {
                    await addRole({ name: value });
                    this.getRoles();
                    this.$message({
                        type: "success",
                        message: "创建成功",
                    });
                })
                .catch(() => { });
        },
        //修改权限
        async handleEdit (scope) {
            this.dialogType = "edit";
            this.dialogVisible = true;
            this.loading = true;
            this.role = deepClone(scope.row);
            try {
                let res = await getRoutes({ roleId: this.role.id });
                let temp1 = res.data || [];
                this.routes = this.generateRoutes(temp1);

                let res2 = await getGameList();
                this.gameList = res2.data || [];

                this.loading = false;
            } catch (err) {
                this.loading = false;
            }
        },
        //pid转树结构
        generateRoutes (routes) {
            let res = [];
            let tmpMap = {};
            routes.forEach((route) => {
                if (
                    route.checked &&
                    (route.pid != -1 || routes.findIndex((s) => s.pid == route.id) == -1)
                ) {
                    this.routesOpen.push(route.id);
                }
                tmpMap[route["id"]] = route;
            });
            routes.forEach((route) => {
                let key = tmpMap[route["pid"]];
                if (key) {
                    if (!key["children"]) {
                        key["children"] = [];
                        key["children"].push(route);
                    } else {
                        key["children"].push(route);
                    }
                } else if (route.pid == -1) {
                    res.push(route);
                }
            });
            return res;
        },
        //确认按钮
        confirmRole () {
            this.$refs.roleForm.validate((valid) => {
                if (valid) {
                    let menuTreeData = this.$refs.tree.getCheckedNodes(false, true);
                    let menuAuth = menuTreeData
                        .map((v) => {
                            return v.id;
                        })
                        .join();
                    let params = {
                        roleId: this.role.id,
                        name: this.role.name,
                        menuAuth,
                        gameAuth: this.role.gameAuth.join(),
                        platformAuth: this.role.platformAuth.join(),
                    };
                    this.submitLoading = true;
                    if (this.dialogType == "edit") {
                        updateRole(params)
                            .then(() => {
                                this.dialogVisible = false;
                                this.submitLoading = false;
                                this.$message({
                                    message: "修改成功",
                                    type: "success",
                                });
                                this.getRoles();
                            })
                            .catch((err) => {
                                console.log(err);
                                this.submitLoading = false;
                            });
                    }
                }
            });
        },
        //关闭弹窗回调
        dialogCloseCallBack () {
            this.routesOpen = [];
            this.$refs.tree.setCheckedKeys([]);
        },
    },
};
</script>

<style lang="scss" scoped>
.role_page {
    ::v-deep .el-tree-node__label {
        overflow: hidden !important;
        white-space: nowrap;
        text-overflow: ellipsis;
        flex: 1;
    }
    .roles-table {
        margin-top: 30px;
    }
    .permission-tree {
        margin-bottom: 30px;
    }
}
</style>
